<template>
	<div class="map">
		<div id="footmarkMap"></div>
		<div class="tools"  v-if="showFlag=='tools'">
			<div class="t1" v-if="!isMoving">
				<div class="t2">
					<ab-button type="hw-primary" @click="trackGo('')">
						路线回放
					</ab-button>
					<i>俯视视角</i>
				</div>
				<div class="t2">
					<ab-button type="hw-success" @click="trackGo('follow')">
						路线回放
					</ab-button>
					<i>跟随视角</i>
				</div>
			</div>
			<div class="t1-row" v-if="isMoving">
				<ab-button :type="mapType == 'vector'?'':'hollow'" circle @click="switchMap">
					{{ mapType == 'vector' ? '卫星' : '矢量' }}
				</ab-button>
				<ab-button :type="trackPause?'hw-success':'hw-warning'" circle @click="trackGo('pause')">
					{{trackPause?'继续':'暂停'}}
				</ab-button>
				<ab-button type="hw-error" circle @click="trackGo('exit')">
					重置
				</ab-button>
			</div>
			<div id="WAY_MOVE_INFO" style="margin: 10px 0;"></div>
			<div class="t1" v-if="!isMoving">
				<ab-button type="error" @click="closeTools">
					退出路线
				</ab-button>
			</div>
		</div>
		<div class="user animation-slideInDown" v-show="showFlag=='userlist'">
			<user-list @getmarks="getMarksList" @userEdit="userEditAction"></user-list>
		</div>
		<div class="user" v-if="showFlag=='useredit'">
			<user-edit ref="USER_EDIT" :data="currentUser" @userEdit="userEditAction" @markdone="markDoneAction"/>
		</div>
	</div>
</template>


<script>
import { nextTick, onMounted, reactive, ref } from '@vue/runtime-core'
import UserList from '@/components/fun_mod/UserList.vue'
import UserEdit from '@/components/fun_mod/UserEdit.vue'
import AbButton from'@/components/able_mod/AbButton.vue'
import useDomMarker from "../hooks/qq-map/useDomMarker"
import useDomWin from "../hooks/qq-map/useDomWin"
import useBounds from "../hooks/qq-map/useBounds"
import useWay from "../hooks/qq-map/useWay"
import $tip from '@/components/able_mod/AbToolTip'
import util from '@/assets/js/util'
import http from '@/axios/http'
import useMarker from '@/hooks/qq-map/useMarker'
export default {
	components: {
		UserList,
		UserEdit,
		AbButton
	},
	setup() {
		onMounted(() => {
			window.onload = loadMapScript()
		})
		// 地图初始参数
		let mapParm = reactive({
			lat: 41.769397,
			lng: 123.428074,
			zoom: 14,
		})
		// 加载腾讯地图
		function loadMapScript() {
			var script = document.createElement("script");
			script.type = "text/javascript"
			script.src = `https://map.qq.com/api/gljs?v=1.exp&key=${util.TMAP_KEY}&libraries=geometry`
			document.body.appendChild(script)
			script.onload = function (e) {
				return new Promise((resolve, reject) => {
					if (typeof (TMap) == 'undefined') {
						tip.value = '腾讯地图插件加载失败'
					} else {
						mapInit()
					}
				})
			}
		}
		// 地图初始化
		var fm = {map: null, marker: null, window: null, cluster: null ,wayMarker: null, wayPolyline: null, wayPath: null}
		function mapInit() {
			fm.map = new TMap.Map(document.getElementById('footmarkMap'), {
				center: new TMap.LatLng(mapParm.lat,mapParm.lng),
				zoom: mapParm.zoom,
			})
			fm.map.on('click',mapClick)
		}
		// 获取打卡记录创建marker
		let marksList = []
		function getMarksList(e) {
			// console.log('markers',e)
			fm = useWay.destroy(fm)
			marksList = e
			fm = useDomMarker(fm,e)
			fm.marker.forEach((dm,i)=>{
				dm.on('click',()=>{
					if (isMoving.value) {
						$tip.message.open('请先重置路线回放',1500,'warning')
						return
					}
					let recIds = []
					let d = dm.dom.data
					for (let i in e) {
						if (d.latitude == e[i].latitude && d.longitude == e[i].longitude) {
							recIds.push(e[i]._id)
						}
					}
					getMarkDetails(d.openId,recIds,'dom-marker')
				})
			})
			useBounds(fm,e)
		}
		// 获取打卡记录明细
		async function getMarkDetails(oid,ids,flag) {
			let g = {}
			g.openId = oid
			g.recIds = JSON.stringify(ids)
			let r = await http.getMarksById(g)
			// console.log(r)
			if (r.code == 10000) {
				if (fm && fm.window) fm.window.index = 0
				let d = r.data
				for(let i in d) {
					let imgs = d[i].imgs
					d[i].imgUrl = (util.isNull(imgs) || util.isNull(imgs[0].img)) ? util.MARKER_IMG : imgs[0].img 
					d[i].markTime = util.formatGmt(d[i].markTime)
				}
				if (flag == 'dom-marker') showDomWin(r.data,0)
				if (flag == 'edit-marker') USER_EDIT.value.showMark(r.data)
			}
		}
		// 记录明细显示到domwin
		function showDomWin(data,i) {
			fm = useDomWin(fm,data,i)
			document.getElementById('DOM_WIN_PREV').addEventListener('click',()=>showDomWin(data,-1))
			document.getElementById('DOM_WIN_NEXT').addEventListener('click',()=>showDomWin(data,1))
			document.getElementById('DOM_WIN_IMG').addEventListener('click',showImg)
			document.getElementById('DOM_WIN_TRACK').addEventListener('click',showTrack)	
		}
		// 点击查看原图
		function showImg() {
			const e = fm.window.dom.data
			util.showRealImg(e.imgUrl,e.title)
		}
		// 显示路线轨迹
		async function showTrack() {
			let ms = marksList
			let d = fm.window.dom.data
			let e = []
			let ee = null
			for (let i in ms) {
				if (d._id == ms[i]._id) {
					e.push(ms[i])
					ee = ms[i*1+1]
					if (ee) e.push(ee)
				}
			}
			if (ee) {
				showFlag.value = 'tools'
				$tip.toast.open('loading')
				fm = await useWay.create(fm,e)
				isMoving.value = false
				useBounds(fm,e)
				if (fm && fm.window) fm.window.setMap(null)
				$tip.toast.close()
			}
			else $tip.message.open('已经是最后一个地点',2500,'warning')
		}
		// 显示工具栏
		let showFlag = ref('userlist')
		// 关闭工具栏并退出路线
		function closeTools() {
			showFlag.value = 'userlist'
			useWay.stop(fm)
			setTimeout(() => {
				fm = useWay.destroy(fm)
				mapType.value = 'satellite'
				switchMap()
			}, 100);
		}
		// 播放路线
		let trackPause = ref(false)
		let isMoving = ref(false)
		function trackGo(f) {
			if (f == 'pause') {
				trackPause.value = !trackPause.value
				useWay.pause(fm,trackPause.value)
			} else if (f == 'exit') {
				useWay.stop(fm)
				setTimeout(() => {
					showTrack()
					isMoving.value = false
					mapType.value = 'satellite'
					switchMap()
				}, 500);
			}
			else {
				useWay.move(fm,60,f)
				isMoving.value = true
			}
		}
		// 切换地图(普通：roadmap，卫星： satellite)
		let mapType = ref('vector')
		function switchMap() {
			mapType.value = mapType.value == 'vector' ? 'satellite' : 'vector'
			let _baseMap = {}
			_baseMap.type = mapType.value
			fm.map.setBaseMap(_baseMap)
		}

		// 用户编辑框操作
		let currentUser = ref()
		function userEditAction(e) {
			// console.log(e)
			markQueryData = null
			if (e.flag == 'CLOSE_USER_EDIT') {
				// 关闭用户编辑窗口并清除编辑marker
				fm = useMarker(fm,'clear')
				showFlag.value = 'userlist'
			} else if (e.flag == 'SHOW_USER_EDIT') {
				// 显示用户编辑窗口并清除查询marker
				fm = useDomMarker(fm,'clear')
				currentUser.value = e
				showFlag.value = 'useredit'
			}
			markQueryData = null
		}

		// 地图点击事件
		let USER_EDIT = ref(null)
		function mapClick(e) {
			if (showFlag.value != 'useredit') return
			if (markDoneStatus == 'markeredit') return
			USER_EDIT.value.addMark(e)
		}

		// 用户编辑新增、修改、查询打卡记录返回值并生成marker
		let markDoneStatus = ''
		let markQueryData = null
		function markDoneAction(markers) {
			let m = markers.data
			if (markers.flag == 'EDIT_MARKER_UPDATE') {
				let recId = m[0].recId
				if (recId) {
					// 删除编辑marker
					for(let i in markQueryData) {
						if (recId == markQueryData[i]._id) {
							markQueryData.splice(i,1)
						}
					}
				} else {
					// 新增编辑marker
					if (!markQueryData) markQueryData = []
					markQueryData.push(m[0])
				}
				m = markQueryData
			}
			if (markers.flag == 'EDIT_MARKER_QUERY') {
				markQueryData = m
			}
			if (m && m.length>0) {
				fm = useMarker(fm,m)
				fm.marker.on("click", (e)=>{
					markDoneStatus = 'markeredit'
					let recIds = []
					let _pos = e.geometry.position
					for (let i in m) {
						if (_pos.lat == m[i].latitude && _pos.lng == m[i].longitude) {
							recIds.push(m[i]._id)
						}
					}
					if (util.isNull(recIds))
						$tip.message.open('没有记录',1500,'warning')
					else
						getMarkDetails(m[0].openId,recIds,'edit-marker')
					nextTick(()=>{
						markDoneStatus = ''
					})
				})
			}
			else fm = useMarker(fm,'clear')
		}

		return {
			mapParm,getMarksList,showFlag,closeTools,trackGo,trackPause,isMoving,mapType,switchMap,
			currentUser,userEditAction,USER_EDIT,markDoneAction
		}
	}
}
</script>

<style lang="scss" scoped>
.map{
	position: fixed;
	top: 0;left: 0;
	width: 100%;height: 100%;
	#footmarkMap{
		width: 100%;height: calc(100vh);
	}
	.user{
		position: fixed;
		top: 25px;left: 25px;
		z-index: 1000;
	}
	.tools{
		max-width: 300px;
		padding: 15px;
		position: fixed;
		top: 25px;left: 25px;
		z-index: 1000;
		background-color: rgba(249,249,249,0.9);
		border-radius: 5px;
		box-shadow: 1px 1px 5px #ccc;
		.t1{
			.t2{
				@extend %view-flex;
				flex-direction: row;
				justify-content: flex-start;
				i{
					font-style: normal;
					font-size: 16px;
					color: #999;
				}
			}
		}
		.t1-row{
			@extend %view-flex;
			flex-direction: row;
		}
	}
}
</style>